<template>
  <div class="book-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" class="search-form">
        <div class="search-item">
          <el-input v-model="searchForm.keyword" placeholder="搜索图书标题、作者、ISBN" clearable @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>

        <div class="search-item">
          <el-select v-model="searchForm.categoryId" placeholder="选择分类" clearable>
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </div>

        <div class="search-item">
          <el-select v-model="searchForm.status" placeholder="图书状态" clearable>
            <el-option label="可借" value="AVAILABLE" />
            <el-option label="已借" value="BORROWED" />
          </el-select>
        </div>

        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </div>
      </el-form>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <div class="table-header">
        <div class="table-title">图书列表</div>
        <div class="table-actions">
          <el-button v-if="userStore.isAdmin" type="primary" @click="$router.push('/books/add')">
            <el-icon>
              <Plus />
            </el-icon>
            添加图书
          </el-button>

          <el-button v-if="userStore.isAdmin && selectedBooks.length > 0" type="danger" @click="handleBatchDelete">
            <el-icon>
              <Delete />
            </el-icon>
            批量删除
          </el-button>
        </div>
      </div>

      <el-table v-loading="loading" :data="books" @selection-change="handleSelectionChange" stripe>
        <el-table-column v-if="userStore.isAdmin" type="selection" width="55" />

        <el-table-column label="封面" width="80">
          <template #default="{ row }">
            <div class="book-cover">
              <img v-if="row.coverUrl" :src="row.coverUrl" :alt="row.title" />
              <div v-else class="default-cover">
                <el-icon>
                  <Reading />
                </el-icon>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="title" label="书名" min-width="150" />

        <el-table-column prop="author" label="作者" width="120" />

        <el-table-column prop="isbn" label="ISBN" width="140" />

        <el-table-column prop="categoryName" label="分类" width="100" />

        <el-table-column prop="publisher" label="出版社" width="120" />

        <el-table-column prop="publishDate" label="出版日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.publishDate) }}
          </template>
        </el-table-column>

        <el-table-column prop="totalCopies" label="总数" width="80" />

        <el-table-column prop="availableCopies" label="可借" width="80" />

        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 'AVAILABLE' ? 'success' : 'warning'" size="small">
              {{ row.status === 'AVAILABLE' ? '可借' : '已借' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button v-if="!userStore.isAdmin && row.status === 'AVAILABLE'" type="primary" size="small"
              @click="handleBorrow(row)">
              借阅
            </el-button>

            <el-button v-if="userStore.isAdmin" type="primary" size="small"
              @click="$router.push(`/books/edit/${row.id}`)">
              编辑
            </el-button>

            <el-button v-if="userStore.isAdmin" type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 借阅对话框 -->
    <el-dialog v-model="borrowDialogVisible" title="借阅图书" width="400px">
      <div class="borrow-info">
        <p><strong>图书：</strong>{{ selectedBook?.title }}</p>
        <p><strong>作者：</strong>{{ selectedBook?.author }}</p>
        <p><strong>可借数量：</strong>{{ selectedBook?.availableCopies }}</p>
      </div>

      <template #footer>
        <el-button @click="borrowDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBorrow" :loading="borrowing">
          确认借阅
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getBookList, deleteBook, batchDeleteBooks } from '@/api/book'
import { getAllCategories } from '@/api/category'
import { borrowBook } from '@/api/borrow'
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Reading
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 加载状态
const loading = ref(false)
const borrowing = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  categoryId: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 数据
const books = ref([])
const categories = ref([])
const selectedBooks = ref([])

// 借阅相关
const borrowDialogVisible = ref(false)
const selectedBook = ref(null)

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

// 加载图书列表
const loadBooks = async () => {
  try {
    loading.value = true

    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }

    const response = await getBookList(params)
    const { data, total } = response

    books.value = data
    pagination.total = total
  } catch (error) {
    console.error('加载图书列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await getAllCategories()
    categories.value = response.data
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadBooks()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    categoryId: '',
    status: ''
  })
  pagination.current = 1
  loadBooks()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadBooks()
}

// 当前页改变
const handleCurrentChange = (current) => {
  pagination.current = current
  loadBooks()
}

// 选择改变
const handleSelectionChange = (selection) => {
  selectedBooks.value = selection
}

// 借阅图书
const handleBorrow = (book) => {
  selectedBook.value = book
  borrowDialogVisible.value = true
}

// 确认借阅
const confirmBorrow = async () => {
  try {
    borrowing.value = true

    await borrowBook({ bookId: selectedBook.value.id })

    ElMessage.success('借阅成功')
    borrowDialogVisible.value = false
    loadBooks()
  } catch (error) {
    console.error('借阅失败:', error)
  } finally {
    borrowing.value = false
  }
}

// 删除图书
const handleDelete = async (book) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除图书「${book.title}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteBook(book.id)
    ElMessage.success('删除成功')
    loadBooks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedBooks.value.length} 本图书吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedBooks.value.map(book => book.id)
    await batchDeleteBooks(ids)

    ElMessage.success('批量删除成功')
    loadBooks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
    }
  }
}

// 初始化
onMounted(() => {
  loadBooks()
  loadCategories()
})
</script>

<style scoped>
.book-list {
  max-width: 1400px;
  margin: 0 auto;
}

.book-cover {
  width: 40px;
  height: 56px;
  border-radius: 4px;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  color: #999;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.borrow-info {
  padding: 20px 0;
}

.borrow-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #333;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-item {
    min-width: auto;
  }

  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>